<template>
  <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
    <div style="
        background-color: #fff;
        margin: 20px 0 0 0;
        box-shadow: 10px 10px 18px 0 rgba(0, 0, 0, 0.12);
        border-radius: 3px;
      ">
      <el-form :model="temp_bussi" :inline="true" ref="temp_bussi" style="text-align: center">
        <el-row style="margin: 1% auto; font-size: 20px">办件查询</el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="开始时间" prop="applyCode">
              <el-date-picker prefix-icon="null" style="padding: 2px" type="date" placeholder="  开始日期"
                v-model="temp_bussi.startTime" value-format="yyyy-MM-dd" :picker-options="pickerOptionsStart"
                @change="startTimeChang"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间" prop="applyCode">
              <el-date-picker prefix-icon="null" style="padding: 2px" type="date" placeholder="  结束日期"
                  v-model="temp_bussi.endTime" value-format="yyyy-MM-dd" :picker-options="pickerOptionsOver"
                  @change="endTimeChang"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="乡镇街道" v-if="townState" prop="townCode">
              <el-select v-model="temp_bussi.townCode" placeholder="请选择乡镇街道">
                <el-option label="请选择乡镇街道" value></el-option>
                <el-option v-for="item in temp_bussi.townList" :key="item.code" :label="item.name" :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="villageState">
            <el-form-item label="村组社区" prop="villageCode">
              <el-select v-model="temp_bussi.villageCode" placeholder="请选择村组社区">
                <el-option label="请选择村组社区" value></el-option>
                <el-option v-for="item in temp_bussi.villageList" :key="item.code" :label="item.name"
                  :value="item.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
        </el-row>

        <el-row :gutter="10">
          <el-col :span="24" style="float: right; padding-right: 70px">
            <el-form-item>
              <el-button type="primary" @click="searchTime('temp_bussi')">搜索</el-button>
              <el-button @click="resetForm('temp_bussi')">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 这个是统计图下面的完成百分比 -->
    <el-tab-pane label="办件量统计" name="first">
      <div id="task" style="min-width: 20%; height: 50%"></div>
      <el-table :data="bussiData" ref="bussiData">
        <el-table-column :label="sname" prop="name" align="center"></el-table-column>
        <el-table-column label="总件量" prop="count" sortable align="center"></el-table-column>
        <el-table-column label="完成量" prop="finished" sortable align="center"></el-table-column>
        <el-table-column label="总件百分比" prop="cpersont" sortable align="center"></el-table-column>
        <el-table-column label="完成百分比" prop="fpersont" sortable align="center"></el-table-column>
        <el-table-column prop="operation" label="详情" align="center" v-if="isshow">
          <template slot-scope="scope">
            <el-link type="primary" @click="getVillageDt(scope.row.code)">详情</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="操作" label="查看" align="center" v-if="isshow">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-search" @click="queryToTown(scope.row)">查询</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>


    <el-dialog title="村组社区" :visible.sync="centerDialogVisible" width="80%" center>
      <span slot="footer" class="dialog-footer">
        <template>
          <el-table :data="villageData" ref="villageData" style="margin-top: 1%">
            <el-table-column label="村组社区" prop="name" align="center"></el-table-column>
            <el-table-column label="总件量" prop="count" sortable align="center"></el-table-column>
            <el-table-column label="完成量" prop="finished" sortable align="center"></el-table-column>
            <el-table-column label="总件百分比" prop="cpersont" sortable align="center"></el-table-column>
            <el-table-column label="完成百分比" prop="fpersont" sortable align="center"></el-table-column>
            <el-table-column prop="操作" label="查看" align="center" v-if="isshow">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-search" @click="queryToVillage(scope.row)">查询</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </span>
    </el-dialog>
    <el-dialog title="效率信息" :visible.sync="centerDialogVisibles" width="80%" center>
      <span slot="footer" class="dialog-footer">
        <template>
          <el-form label-position="left" inline class="demo-table-expand">
            <el-table :data="villageCountData" ref="villageCountData">
              <el-table-column label="村组社区" prop="townName" align="center"></el-table-column>
              <el-table-column label="完成量" prop="count" align="center"></el-table-column>
              <el-table-column label="平均耗时（天）" prop="useTime" sortable align="center"></el-table-column>
            </el-table>
            <!-- <el-form-item label="行政村名称"></el-form-item>  -->
          </el-form>
        </template>
      </span>
    </el-dialog>
    <el-tab-pane label="效率统计" name="second">
      <el-card>
        <div id="efficiency" style="min-width: 20%; height: 50%"></div>
      </el-card>
      <el-card>
        <!-- <div style="text-aglin:center">最快办件排行</div> -->
        <el-table :data="efficiencyData" ref="bussiData">
          <el-table-column label="乡镇名称" prop="townName" align="center"></el-table-column>
          <el-table-column label="完成量" prop="count" align="center"></el-table-column>
          <el-table-column label="平均耗时（天）" prop="useTime" sortable align="center"></el-table-column>
          <el-table-column prop="operation" v-if="isShowCount" label="详情" align="center">
            <template slot-scope="scope">
              <el-link type="primary" @click="getVillageCountDt(scope.row.code)">详情</el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-tab-pane>
  </el-tabs>
</template>
<script>
  import HighCharts from "highcharts";
  import {
    staticStreetApi,
    villageCountApi,
    streetLikeSelect,
    enfficiencyApi,
  } from "@/api/statistics/statisticsApi";
  import store from "@/vuex/store";
  import {
    getChildrenAddress
  } from "@/api/addressDictionary";
  export default {
    data() {
      return {
        addressCode: store.getters.addressCode,
        currentCode: store.getters.currentCode,
        activeName: "first",
        sname: "",
        centerDialogVisible: false,
        centerDialogVisibles: false,
        bussiData: [],
        villageData: [],
        villageCountData: [],
        efficiencyData: [],
        isshow: false,
        isShowCount: false,
        townState: false, //乡镇查询框默认不显示
        villageState: false,
        temp_bussi: {
          startTime: "", //开始时间
          endTime: "", //结束时间
          applyCode: "",
          region: "",
          idCard: "",
          address: "",
          addressCode: store.getters.currentCode,
          name: "",
          townList: [{
            name: "",
            code: ""
          }],
          villageList: [{
            name: "",
            code: ""
          }],
          townCode: "",
          villageCode: "",
          currentPage: 1,
          pageSize: 5,
          total: 0,
        },
        pickerOptionsStart: {
          disabledDate(time) {
            return time.getTime() < 1488297600000 || time.getTime() >= Date.now();
          },
        },
        pickerOptionsOver: {
          disabledDate(time) {
            return time.getTime() < 1488297600000 || time.getTime() >= Date.now();
          },
        },
        taskOption: {
          credits: {
            enabled: false
          },
          chart: {
            type: "column",
          },
          title: {
            text: "乡镇办件量",
          },
          xAxis: {
            categories: [],
            crosshair: true,
          },
          yAxis: {
            allowDecimals: false,
            min: 0,
            title: {
              text: "办件量（件）",
            },
          },
          tooltip: {
            // head + 每个 point + footer 拼接成完整的 table
            headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
            pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
              '<td style="padding:0"><b>{point.y} 件</b></td></tr>',
            footerFormat: "</table>",
            shared: true,
            useHTML: true,
          },
          plotOptions: {
            column: {
              borderWidth: 0,
            },
          },
          series: [{
              name: "总件量",
              data: [],
            },
            {
              name: "完成量",
              data: [],
            },
          ],
        },
        efficiencyOption: {
          credits: {
            enabled: false
          },
          chart: {
            type: "column",
          },
          title: {
            text: "办件效率排行",
          },
          xAxis: {
            categories: [],
            crosshair: true,
          },
          yAxis: {
            min: 0,
            title: {
              text: "平均耗时（天）",
            },
          },
          tooltip: {
            // head + 每个 point + footer 拼接成完整的 table
            headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
            pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
              '<td style="padding:0"><b>{point.y:.1f} 天</b></td></tr>',
            footerFormat: "</table>",
            shared: true,
            useHTML: true,
          },
          plotOptions: {
            column: {
              borderWidth: 0,
            },
          },
          series: [{
            name: "所耗时间",
            data: []
          }],
        },
      };
    },
    created: function () {
      this.getEfficiencyStatistics();
      this.getStreetStatistics();
      getChildrenAddress(this.currentCode).then((townList) => {
        if (this.currentCode.length > 9) {
          this.temp_bussi.townList = townList.data.data;
        } else {
          this.temp_bussi.villageList = townList.data.data;
        }
      });
    },
    methods: {
      // queryToTown跳转到查询页面
      queryToTown(row){
        this.$router.push({
          path: "./search",
          query: row,
        });
      },

      //queryToVillage
      queryToVillage(row){
        this.$router.push({
          path: "./search",
          query: row,
        });
      },

      //重置
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.temp_bussi.startTime = "";
        this.temp_bussi.endTime = "";
        if (this.currentCode.length > 9) {
          this.isshow = true;
          this.sname = "行政街道";
        } else {
          this.sname = "村组社区";
          this.isshow = false;
        }
        staticStreetApi(this.currentCode)
          .then((res) => {
            let street = [];
            let totalCount = [];
            let finishedConunt = [];
            if (res.data.data) {
              this.bussiData = res.data.data;
              var bussiData = [];
              for (let i = 0; i < res.data.data.length; i++) {
                var obj = {};
                obj.code = res.data.data[i].code;
                obj.name = res.data.data[i].name;
                obj.count = res.data.data[i].count;
                obj.finished = res.data.data[i].finished;
                obj.cpersont = res.data.data[i].cpersont;
                obj.fpersont = res.data.data[i].fpersont;
                if (
                  res.data.data[i].fpersont == "" ||
                  res.data.data[i].fpersont == null
                ) {
                  obj.fpersont = "0.00%";
                } else {
                  obj.fpersont = res.data.data[i].fpersont;
                }
                if (
                  res.data.data[i].cpersont == "" ||
                  res.data.data[i].cpersont == null
                ) {
                  obj.cpersont = "0.00%";
                } else {
                  obj.cpersont = res.data.data[i].cpersont;
                }
                bussiData[i] = obj;
              }
              this.bussiData = bussiData;
              res.data.data.forEach((element) => {
                street.push(element.name);
                totalCount.push(element.count);
                finishedConunt.push(element.finished);
              });
              this.taskOption.xAxis.categories = street;
              this.taskOption.series[0].data = totalCount;
              this.taskOption.series[1].data = finishedConunt;
              this.taskChart();
            }
          })
          .catch((err) => {
            this.$message.info("办件量暂无数据");
          });
      },
      //查询
      searchTime(formName) {
        this.$refs[formName].validate((valid) => {
          if (this.temp_bussi.townCode != "") {
            this.isshow = false;
            this.sname = "村组社区";
            //查询当前乡镇
            staticStreetApi(this.temp_bussi.townCode)
              .then((res) => {
                let street = [];
                let totalCount = [];
                let finishedConunt = [];
                if (res.data.data) {
                  res.data.data.forEach((element) => {
                    if (element.cpersont == "" || element.cpersont == null) {
                      element.cpersont = "0.00%";
                    }
                    if (element.fpersont == "" || element.fpersont == null) {
                      element.fpersont = "0.00%";
                    }
                    street.push(element.name);
                    totalCount.push(element.count);
                    finishedConunt.push(element.finished);
                  });
                  this.bussiData = res.data.data;
                  this.taskOption.xAxis.categories = street;
                  this.taskOption.series[0].data = totalCount;
                  this.taskOption.series[1].data = finishedConunt;
                  this.taskChart();
                }
              })
              .catch((err) => {
                this.bussiData = [];
                this.$message.info(err.data.respondMessage);
              });
          } else {
            streetLikeSelect(this.temp_bussi)
              .then((response) => {
                response.data.data.items.forEach((element) => {
                  if (element.fpersont == "" || element.fpersont == null) {
                    element.fpersont = "0.00%";
                  }
                  if (element.cpersont == "" || element.cpersont == null) {
                    element.cpersont = "0.00%";
                  }
                });
                this.bussiData = response.data.data.items;
                this.$message({
                  showClose: true,
                  message: "搜索成功",
                  type: "success",
                });
              })
              .catch((error) => {
                this.$message({
                  message: error.data.respondMessage,
                  type: "error",
                });
              });
          }
        });
      },
      dateFilter: function (input) {
        var d = new Date(input);
        var year = d.getFullYear();
        var month =
          d.getMonth() < 9 ? "0" + (d.getMonth() + 1) : "" + (d.getMonth() + 1);
        var day = d.getDate() < 10 ? "0" + d.getDate() : "" + d.getDate();
        // var hour = d.getHours();
        // var minutes = d.getMinutes();
        // var seconds = d.getSeconds();
        return year + "-" + month + "-" + day;
      },
      startTimeChang(val) {
        let startTime = this.dateFilter(val);
        this.temp_bussi.startTime = startTime;
      },
      endTimeChang(val) {
        let endTime = this.dateFilter(val);
        this.temp_bussi.endTime = endTime;
      },
      handleClick(tab, event) {
        // console.log(tab, event);
      },
      taskChart() {
        HighCharts.chart("task", this.taskOption);
      },
      efficiencyChart() {
        HighCharts.chart("efficiency", this.efficiencyOption);
      },
      getVillageDt(code) {
        this.centerDialogVisible = true;
        staticStreetApi(code)
          .then((res) => {
            if (res.data.data) {
              res.data.data.forEach((element) => {
                if (element.cpersont == "" || element.cpersont == null) {
                  element.cpersont = "0.00%";
                }
                if (element.fpersont == "" || element.fpersont == null) {
                  element.fpersont = "0.00%";
                }
              });
              this.villageData = res.data.data;
            }
          })
          .catch((err) => {
            this.villageData = [];
            this.$message.info(err.data.respondMessage);
          });
      },
      getStreetStatistics() {
        if (this.currentCode.length > 9) {
          this.townState = true;
          this.isshow = true;
          this.isShowCount = true;
          this.sname = "乡镇街道";
        } else {
          this.villageState = true;
          this.isshow = false;
          this.isShowCount = false;
          this.sname = "村组社区";
        }
        staticStreetApi(this.currentCode)
          .then((res) => {
            let street = [];
            let totalCount = [];
            let finishedConunt = [];
            if (res.data.data) {
              this.bussiData = res.data.data;
              res.data.data.forEach((element) => {
                if (element.cpersont == "" || element.cpersont == null) {
                  element.cpersont = "0.00%";
                }
                if (element.fpersont == "" || element.fpersont == null) {
                  element.fpersont = "0.00%";
                }
                street.push(element.name);
                totalCount.push(element.count);
                finishedConunt.push(element.finished);
              });
              this.taskOption.xAxis.categories = street;
              this.taskOption.series[0].data = totalCount;
              this.taskOption.series[1].data = finishedConunt;
              this.taskChart();
            }
          })
          .catch((err) => {
            this.$message.info(err.data.respondMessage);
          });
      },
      getVillageCountDt(code) {
        this.centerDialogVisibles = true;
        villageCountApi(code)
          .then((res) => {
            //villageCountData

            if (res.data.data.length != 0) {
              var villageCountData = [];
              for (let i = 0; i < res.data.data.length; i++) {
                var obj = {};
                obj.townName = res.data.data[i].townName;
                obj.count = res.data.data[i].count;
                obj.useTime = res.data.data[i].useTime;
                villageCountData[i] = obj;
              }
              this.villageCountData = villageCountData;
            }
          })
          .catch((err) => {
            this.villageCountData = [];
            this.$message.info(err.data.respondMessage);
          });
      },

      getEfficiencyStatistics() {
        enfficiencyApi(this.currentCode)
          .then((res) => {
            let townList = [];
            let useTimeList = [];
            if (res.data.data) {
              this.efficiencyData = res.data.data;
              res.data.data.forEach((element) => {
                townList.push(element.townName);
                useTimeList.push(element.useTime);
              });
              this.efficiencyOption.xAxis.categories = townList;
              this.efficiencyOption.series[0].data = useTimeList;
              this.efficiencyChart();
            }
          })
          .catch((error) => {
            this.$message({
              showClose: true,
              message: error,
              type: "error",
            });
          });
        // enfficiencyApi(this.currentCode)
        //   .then(res => {
        //     console.log(this.currentCode)
        //     let townList = [];
        //     let useTimeList = [];
        //     if (res.data.data) {
        //       this.efficiencyData = res.data.data;
        //       res.data.data.forEach(element => {
        //         townList.push(element.townName);
        //         useTimeList.push(element.useTime);
        //       });
        //       this.efficiencyOption.xAxis.categories = townList;
        //       this.efficiencyOption.series[0].data = useTimeList;
        //       this.efficiencyChart();
        //     }
        //   })
        //   .catch(err => {
        //     this.$message({
        //       showClose: true,
        //       message: err.data,
        //       type: "error",
        //     });
        //   });
      },
    },
    mounted() {
      // this.taskChart();
      //this.getEfficiencyStatistics();
    },
  };
</script>
<style>
  .el-tabs__nav-scroll {
    padding-top: 20px;
  }

  .el-tabs__nav .is-top {
    background-color: #fff;
  }

  .el-tabs__header {
    margin: 0;
  }

  .el-steps--horizontal {
    padding: 20px 0 20px 0;
  }
</style>